 //控制层 
app.controller('typeTemplateController' ,function($scope,$controller,brandService,specificationService,typeTemplateService){
	
	$controller('baseController',{$scope:$scope});//继承
	
    //读取列表数据绑定到表单中  
	$scope.findAll=function(){
		typeTemplateService.findAll().success(
			function(response){
				$scope.list=response;
			}			
		);
	}    
	
	//分页
	$scope.findPage=function(){
		typeTemplateService.findPage($scope.paginationConf.currentPage,$scope.paginationConf.itemsPerPage).success(
			function(response){
				$scope.list=response.rows;	
				$scope.paginationConf.totalItems=response.total;//更新总记录数
			}			
		);
	}
	
	//查询实体 
	$scope.findOne=function(id){				
		typeTemplateService.findOne(id).success(
			function(response){
				$scope.entity= response;
				//转换品牌列表、规格列表、扩展属性列表
				$scope.entity.brandIds=JSON.parse(response.brandIds); //让品牌下拉框自动选中
				$scope.entity.specIds=JSON.parse(response.specIds);	  //让规格下拉框自动选中
				$scope.entity.customAttributeItems=JSON.parse(response.customAttributeItems); //为了遍历扩展属性
			}
		);				
	}
	
	//保存 
	$scope.save=function(){				
		var serviceObject;//服务层对象  				
		if($scope.entity.id){//如果有ID
			serviceObject=typeTemplateService.update( $scope.entity ); //修改  
		}else{
			serviceObject=typeTemplateService.add( $scope.entity  );//增加 
		}				
		serviceObject.success(
			function(response){
				if(response.success){
					//重新查询 
		        	$scope.findPage();
				}else{
					alert(response.message);
				}
			}		
		);				
	}
	
	 
	//批量删除 
	$scope.dele=function(){			
		//获取选中的复选框			
		typeTemplateService.dele( $scope.selectIds ).success(
			function(response){
				if(response.success){
					$scope.findPage();//刷新列表
					$scope.selectIds=[];
				}						
			}		
		);				
	}
	
	$scope.searchEntity={};//定义搜索对象 
	
	//搜索
	$scope.search=function(page,rows){			
		typeTemplateService.search(page,rows,$scope.searchEntity).success(
			function(response){
				$scope.list=response.rows;	
				$scope.paginationConf.totalItems=response.total;//更新总记录数
			}			
		);
	}

	//查询所有的品牌列表
	$scope.findSpecList=function () {
		specificationService.findSpecList().success(function (response) {
			$scope.specList = {data:response};
		})
	}
	//查询所有的规格列表
	$scope.selectBrandList=function () {
		brandService.selectBrandList().success(function (response) {
			$scope.brandList = {data:response};
		})
	}
    //添加扩展属性选项
	$scope.addItem=function () {
		$scope.entity.customAttributeItems.push({});
	}
	//删除扩展属性中的某一项
	$scope.delRow=function (index) {
		$scope.entity.customAttributeItems.splice(index, 1);
	}
	//将json字符串按照给定的key连接成一个字符串
	$scope.jsonToString=function (jsonStr,key) {
		//1.将输入的json串转换为json对象
		var json = JSON.parse(jsonStr);
		//2.遍历json对象，按照指定的key得到其值，并连接
		var info = "";   //存放连接的字符串
		for (var i=0;i<json.length;i++){
			info += json[i][key] + ","
		}
		//3.将最后多余一个逗号删除
		let str = info.substr(0,info.length-1);
		return str;

	}
});	
